﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Drawing;
using System.Collections.Generic;

using AzureWcfPage;


namespace AzureConfigConsumer.ConfigData
{
    [ToolboxItemAttribute(false)]
    public class ConfigData : WebPart
    {

        private string CACHE_NAME = "AzureConfigConsumerCacheSample";
        private int CACHE_TIME = 10;

        private string CACHE_LAST = string.Empty;


        protected override void CreateChildControls()
        {
            Label statusLbl = new Label();
            string cachedLast = string.Empty;

            try
            {
                //create a var of the type of configuration data we want to retrieve
                AzureWcfPage.CustomersWCF.Customer[] Customers = null;

                //look for our item in cache
                if (HttpContext.Current.Cache[CACHE_NAME] != null)
                {
                    //if we find, it cast it to our type and pull it out of cache
                    Customers = (AzureWcfPage.CustomersWCF.Customer[])HttpContext.Current.Cache[CACHE_NAME];

                    //get when we cached it 
                    cachedLast = (string)HttpContext.Current.Cache[CACHE_LAST];
                }
                else
                {
                    //if it's not in cache, then retrieve it and put it into cache

                    //create an instance of the control
                    AzureWcfPage.WcfDataControl cfgCtrl = new AzureWcfPage.WcfDataControl();

                    //set the properties to retrieve data
                    cfgCtrl.WcfUrl = "https://azurewcf.vbtoys.com/Customers.svc";
                    cfgCtrl.OutputType = AzureConnect.WcfConfig.DataOutputType.ServerCache;
					cfgCtrl.ServerCacheName = CACHE_NAME;
                    cfgCtrl.ServerCacheTime = CACHE_TIME;
                    cfgCtrl.MethodName = "GetAllCustomers";

                    //execute the method
                    bool success = cfgCtrl.ExecuteRequest();

                    if (success)
                    {
                        //get the strongly typed version of our data
                        //the data type needs to come from the control we are creating
                        Customers = (AzureWcfPage.CustomersWCF.Customer[])cfgCtrl.QueryResultsObject;

                        //if you wanted the Xml representation of the object you can get
                        //it from QueryResultsString
                        string stringCustomers = cfgCtrl.QueryResultsString;

                        //just storing the last time we retrieved data for demo purposes
                        cachedLast = DateTime.Now.ToString();
                        HttpContext.Current.Cache.Insert(CACHE_LAST, cachedLast, null,
                            DateTime.Now.AddMinutes(CACHE_TIME), 
                            System.Web.Caching.Cache.NoSlidingExpiration);
                    }
                    else
                    {
                        //there was some problem and we weren't able to get our data
                        statusLbl.ForeColor = Color.Red;
                        statusLbl.Text = "Unable to retrieve Azure configuration data";

						if (!string.IsNullOrEmpty(cfgCtrl.ExecutionErrorMessage))
							statusLbl.Text += "; the error message returned was " +
								cfgCtrl.ExecutionErrorMessage;

						//if we wanted the exact details we could use 
						//cfgCtrl.ExecutionErrorMessage to see the error message, 
						//cfgCtrl.ExecutionServerName to see the name of the server where 
						//the request executed and cfgCtrl.TraceInfoMessage to see details
						//about our request, such as the method name and parameters used
						//the time it took to execute the request, etc.
                    }
                }

                //see if we got our data
                if (Customers != null)
                {
                    //add a grid and bind it to the list
                    DataGrid dg = new DataGrid();
                    dg.DataSource = Customers;
                    dg.DataBind();

                    this.Controls.Add(dg);

                    //show the last time we retrieved the data
                    //update status
                    statusLbl.ForeColor = Color.Green;
                    statusLbl.Text = "<br/>Data retrieved at " + cachedLast;
                }
            }
            catch (Exception ex)
            {
                statusLbl.ForeColor = Color.Red;
                statusLbl.Text = "There was an error: " + ex.Message;
            }

            this.Controls.Add(statusLbl);
        }
    }
}
